# -*- coding: utf-8 -*-
class MovingObj:

    def __init__(self, x, y):
        """

        :param x: 物体判定中心点
        :param y: 物体判定中心点
        """
        self.x = x
        self.y = y
        self.current_direction = 'down'
        self.direction_logs = []
        self.resource_dict = {}
        self.grid_width = 40
        self.grid_height = 40
        self.gif_index = {'up':0,'down':0,'left':0,'right':0}
        self.align_to_bot= True
       
    def reset_other_direction_index(self):
        '''
        重置帧index
        :return:
        '''
        for direction in self.gif_index:
            if direction != self.current_direction:
                self.gif_index[direction] = 0

    def update(self, x, y, direction):
        '''
        更新方向 和  帧index
        :param x:
        :param y:
        :param direction:
        :return:
        '''
        self.x = x
        self.y = y
        self.current_direction = direction
        self.direction_logs.append(direction)
        self.gif_index[direction] +=1
        self.reset_other_direction_index()
        if self.resource_dict[direction] != []:
            self.gif_index[direction] =  self.gif_index[direction] % len(self.resource_dict[direction])

    def register_walk_pic(self, resource_cache):
        """
        注册一个资源 dict，读取人物动图
        :param resource_cache:
        :return:
        """
        self.resource_dict = resource_cache

    def get_screen_display_coordinate(self):
        """
        根据当前物体中心点 推算显示 位置
        :return:
            
        """
        if self.align_to_bot:
            y_ = self.y+    0.5 * self.grid_height -  self.resource_dict['down'][0].height 
            return self.x -  0.5 *   self.resource_dict['down'][0].width    ,  y_
        return self.x -  0.5 * self.grid_width,self.y-  0.5 * self.grid_height

    def current_frame_index_toward_direction(self,direction=None):
        '''
        获取当前方向当前帧index
        :param direction:
        :return:
        '''
        if not direction:
            direction = self.current_direction
        return self.gif_index[direction]

    def get_current_frame(self):
        '''
        获得当前帧图片png
        :return:
        '''
        direction_imgs =  self.resource_dict.get(self.current_direction,[])
        if direction_imgs != []:
            print('return direction_imgs')
            return direction_imgs[self.current_frame_index_toward_direction()]
        print('direction_imgs = []')
        return None

    def show_image(self,draw_fun):
        '''
        在游戏里显示帧
        :param draw_fun:
        :return:
        '''
        print('display!!!!!')
        x,y = self.get_screen_display_coordinate()
        frame = self.get_current_frame()
        if frame:
            draw_fun(frame,x,y)
        else:
            print('no frame')



